package utility;

import java.io.*;

public class ByteBufferInputStream extends InputStream {

   private byte[] buffer;
   private int length;
   private int pos = 0;
   
   public ByteBufferInputStream(byte[] buffer) {
      this.buffer = buffer;
      this.length = buffer.length;
   }
   
   public ByteBufferInputStream(byte[] buffer, int length) {
      this.buffer = buffer;
      this.length = length;
   }
   
   public byte[] getBuffer () {
      return this.buffer;
   }

   @Override
   public int read() throws IOException {
      
      if (pos >= this.length) {
         return -1;
      }
      
      return buffer[pos++];
   }
   
   @Override
   public int read(byte[] buffer) throws IOException {
      return this.read(buffer, 0, buffer.length);
   }
   
   @Override
   public int read (byte[] buffer, int offset, int length) throws IOException {
      
      int remaining = this.length - this.pos;
      int read = (remaining < length ? remaining : length);
      
      if (remaining <= 0)
         return -1;
      
      System.arraycopy(this.buffer, this.pos, buffer, offset, read);
      this.pos += read;
      
      return read;
   }
   
}
